layui.use([ 'form', 'table', 'jquery'], function(){
	  var table = layui.table;
	  var form = layui.form;
	  var moduleText;
	  var rolePermission;
	  var $ = layui.$, active = {
			//根据菜单条件查询权限
		    reload: function(){
		    	var moduleSelectId = $('#moduleSelectId');
		        var menuSelectId = $('#menuSelectId');
			      //执行重载
			      table.reload('syspermissionReload', {
			    	 page:false,
			         where: {
			            id: menuSelectId.val(),
			            parent_id: moduleSelectId.val()
			        }
			      });
		    },
		    
		};
	  
	  
	//获取菜单和模块下拉框
	  $.ajax({ 
	       type: "post", 
	       url: "../../syspermission/getSyspermissionSelect", 
	       async:false, 
	       success: function(data){ 
	    	     moduleText = data.data;
		    	 var menuSelectId = document.getElementById("menuSelectId");
		  		 var moduleSelectId = document.getElementById("moduleSelectId");
		  		 var formMenuSelect = document.getElementById("formMenuSelect");
		  		 var formModuleSelect = document.getElementById("formModuleSelect");
		  		 moduleSelectId.options.add(new Option("",""));
		  		 menuSelectId.options.add(new Option("",""));
		  		 $.each(moduleText, function(index, data) {
		  				if(data.type==1){
		  					menuSelectId.options.add(new Option(data.title,data.id));
		  					formMenuSelect.options.add(new Option(data.title,data.id));
		  				}else if(data.type==2){
		  					moduleSelectId.options.add(new Option(data.title,data.id));
		  					formModuleSelect.options.add(new Option(data.title,data.id));
		  				}	
		  		 });
		  		 form.render('select');
	       } 

	 });
	  
	  //获取角色下拉框
	  $.ajax({ 
	       type: "post", 
	       url: "../../sysrole/roleSelection", 
	       async:false, 
	       success: function(data){ 
	    	  var role = JSON.parse(data);
	 		  var roleData = role.sysrole;
	 		  var roleSelectId = document.getElementById("roleSelectId")
	 		  $.each(roleData, function(index, data) {
	 			    if(index == 0){
	 			    	$.post('/role_permission/getPermissionIdByRoleId',{role_id:data.id},function(data){
	 			    		rolePermission = data.data;	 			    		
	 			    	});
	 			    }
	 				roleSelectId.options.add(new Option(data.name,data.id));		
	 		  });
	 		  form.render('select');
	       } 
	 });
	  
	  table.render({
			elem: '#syspermissionTable',
			url: '../../syspermission/getSyspermissionTable',
			toolbar: true,
			even: true,
		    title: '权限管理表',
		    cols:[[
		    	{type : 'checkbox', fixed: 'left'},
		    	{field: 'id',title: 'ID',sort: true, fixed: 'left'},
		    	{field: 'title',title: '名称',sort: true},
		    	{field: 'href',title: '路径',sort: true},
		    	{field: 'parent_id',title: '所属模块',sort: true},
		    	{field: 'type',title: '类型',sort: true},
		    	{fixed : 'right',title : '操作',toolbar : '#barSyspermission',width : 150}
		    ]],
	        page: false,
		    height: $(window).height() -50,
		    id: 'syspermissionReload',
		    done : function(res) {	
				$("[data-field='parent_id']").children().each(function() {
					for(var i = 0; i < moduleText.length; i++){
						if ($(this).text() == moduleText[i].id) {
							$(this).text(moduleText[i].title);
							break;
						}
					}
				});
				$("[data-field='type']").children().each(function() {
					if ($(this).text() == '2') {
						$(this).text("模块");
					}else if($(this).text() == '3'){
						$(this).text("页面");
					}else if($(this).text() == '1'){
						$(this).text("菜单");
					}
				});
				
				//在缓存中找到rolePermission ,然后设置data表格中的选中状态
	            //循环所有数据，找出对应关系，设置checkbox选中状态
				 for(var i=0;i<res.data.length;i++){
	                for(var j=0;j<rolePermission.length;j++){
	                    if(res.data[i].id==rolePermission[j]){
	                        //这里才是真正的有效勾选
	                        res.data[i]["LAY_CHECKED"]='true';
	                        //找到对应数据改变勾选样式，呈现出选中效果
	                        var index= res.data[i]['LAY_TABLE_INDEX'];
	                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
	                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
	                    }
	                }
		          }
				 
				//设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
	            var checkStatus = table.checkStatus('syspermissionReload');
	            if(checkStatus.isAll){
	                $(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
	                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
	            }
			}
	});
	  
	  
	 
	 //菜单下拉栏改变时，模块下拉栏的内容也跟着改变
	 function reloadModuleByMenuSelect(){
		 var menuSelectId = $('#menuSelectId');
		 $.ajax({ 
		       type: "post", 
		       url: "../../syspermission/getSyspermissionByMenuId", 
		       async:false, 
		       data: {menuId:menuSelectId.val()}, 
		       success: function(data){ 
		    	  var moduleSelect = data.data;
				  var moduleSelectId = document.getElementById("moduleSelectId");
				  $('#moduleSelectId').empty();
				  moduleSelectId.options.add(new Option("",""));
				  $.each(moduleSelect, function(index, data) {
					  moduleSelectId.options.add(new Option(data.title,data.id));		
				  });
				  form.render('select');
		       } 

		});
		
	 }
	 
	
	 //角色下拉框变动时重新给rolePermissio赋值
	 function reloadCheckBoxByRoleId(role_id){
		 $.post('../../role_permission/getPermissionIdByRoleId',{role_id:role_id},function(data){
	    		rolePermission = data.data;	 			    		
	    	});
	 }
	 
	   //监听菜单下拉框
	 form.on("select(menuSelectFilter)",function(data){
		 reloadModuleByMenuSelect();
	  	 active.reload();
	 });
	   
	 //监听模块下拉框
	 form.on("select(moduleSelectFilter)",function(data){
	  	 active.reload();
	 });
	 
	//监听角色下拉框
	 form.on("select(roleSelectFilter)",function(data){
		 var role_id = $("#roleSelectId").val();
		 reloadCheckBoxByRoleId(role_id);
		 active.reload();
	 });
	 
	 form.on('submit(demo1)',function(data){
		 var checkedPermission = table.checkStatus('syspermissionReload').data;
		 var moduleSelectId = $('#moduleSelectId');
	     var menuSelectId = $('#menuSelectId');
	     var roleSelectId = $('#roleSelectId');
	     $.ajax({ 
		       type: "post", 
		       url: "../../role_permission/savePermissionByRoleId", 
		       async:false, 
		       data: {moduleId:moduleSelectId.val(),menuId:menuSelectId.val(),data:JSON.stringify(checkedPermission),role_id:roleSelectId.val()}, 
		       success: function(data){
		    	  if(data == "0"){
		    		  layer.msg("保存失败");
		    	  }else if(data == "1"){
		    		  layer.msg("保存成功");
		    	  }else{
		    		  layer.msg("未知错误");
		    	  }
		       } 

		});
	 });
	 
	 
	 $("#addPermissionBtn").click(function(){
		 layer.open({
			type:1,
			title : "添加权限",
			skin : "myclass",
			area : [ "40%" ],
			btn : [ '保存', '取消' ],
			content : $("#PermissionrAdd"),
			success: function(layero){
				document.getElementById("addPermissionForm").reset();
				$("#formTypeSelect").attr("disabled",false);
				$("#formHrefInput").attr("disabled",true);
				$("#formMenuSelect").attr("disabled",true);
				$("#formModuleSelect").attr("disabled",true);
				form.render();
			},
			yes: function(index , layero){
				var formTypeSelect =  $("#formTypeSelect").val();
				var formHrefInput =  $("#formHrefInput").val();
				var formMenuSelect =  $("#formMenuSelect").val();
				var formModuleSelect =  $("#formModuleSelect").val();
				var formTitleInput =  $("#formTitleInput").val();
				var object = {};
				if(formTypeSelect == "3"){
					if(formHrefInput == "" || formHrefInput == null){
						layer.msg("路径不能为空");
						return;
					}
					if(formModuleSelect == "" || formModuleSelect == null){
						layer.msg("父模块不能为空");
						return;
					}
					if(formTitleInput == "" || formTitleInput == null){
						layer.msg("名称不能为空");
						return;
					}
					object["title"] = formTitleInput;
					object["type"] = formTypeSelect;
					object["parent_id"] = formModuleSelect;
					object["href"] = formHrefInput;
				}else if (formTypeSelect == "2"){
					if(formMenuSelect == "" || formMenuSelect == null){
						layer.msg("父菜单不能为空");
						return;
					}
					if(formTitleInput == "" || formTitleInput == null){
						layer.msg("名称不能为空");
						return;
					}
					object["title"] = formTitleInput;
					object["type"] = formTypeSelect;
					object["parent_id"] = formMenuSelect;
					object["href"] = formHrefInput;
				}else if(formTypeSelect == "1"){
					if(formTitleInput == "" || formTitleInput == null){
						layer.msg("名称不能为空");
						return;
					}
					object["title"] = formTitleInput;
					object["type"] = formTypeSelect;
				}else{
					layer.msg("请选先择类型");
					return;
				}
				 $.ajax({ 
				       type: "post", 
				       contentType: "application/json;charset=utf-8",
				       url: "../../syspermission/saveSyspermission", 
				       data: JSON.stringify(object), 
				       success: function(data){
				    	  if(data == "0"){
				    		  layer.msg("新加权限失败");
				    		  layer.close(index);
				    	  }else if(data == "1"){
				    		  layer.msg("新加权限成功");
				    		  layer.close(index);
				    	  }else{
				    		  layer.msg("未知错误");
				    	  }
				       } 
				});
			}
		 });
	 });
	 
	 form.on('select(formTypeFIlter)',function(data){
		 $("#formHrefInput").attr("disabled",true);
		 $("#formHrefInput").addClass("layui-disabled");
			$("#formMenuSelect").attr("disabled",true);
			$("#formModuleSelect").attr("disabled",true);
			form.render();
		 if($("#formTypeSelect").val() == "3"){
			    $("#formHrefInput").attr("disabled",false);
			    $("#formHrefInput").removeClass("layui-disabled");
				$("#formModuleSelect").attr("disabled",false);
				form.render();
		 }else if($("#formTypeSelect").val() == "2"){
			    $("#formHrefInput").attr("disabled",false);
			    $("#formHrefInput").removeClass("layui-disabled");
				$("#formMenuSelect").attr("disabled",false);
				$("#formHrefInput").attr('placeholder','模块的路径可以为空')
				form.render();
		 }else{
			 
		 }
	 });
	 

		//监听行工具事件
			table.on('tool(syspermissionFilter)', function(obj) {
				var data = obj.data;
				if (obj.event === 'del') {
					layer.confirm('真的删除此权限吗?', function(index) {
						$.ajax({ 
						       type: "post", 
						       url: "../../syspermission/deleteSyspermissionById", 
						       data: {id:data.id}, 
						       success: function(data){
						    	  if(data == "0"){
						    		  layer.msg("删除权限失败");
						    	  }else if(data == "1"){
						    		  layer.msg("删除权限成功");	
						    		  obj.del();
						    	  }else{
						    		  layer.msg("未知错误");
						    	  }
						       } 
						});
						layer.close(index);
					});
				} else if (obj.event === 'edit') {
					/* 再弹出编辑界面 */
					layer.open({
						type : 1,
						title : "编辑权限",
						skin : "myclass",
						area : [ "40%" ],
						btn : [ '保存', '取消' ],
						content : $("#PermissionrAdd"),
						success : function(layero) {
							document.getElementById("addPermissionForm").reset();
							$("#formHrefInput").attr("disabled",true);
							$("#formMenuSelect").attr("disabled",true);
							$("#formModuleSelect").attr("disabled",true);
							$('#formTypeSelect').val(data.type);
							$('#formTypeSelect').attr("disabled",true);
							if(data.type == "3"){
								$("#formModuleSelect").attr("disabled",false);
								$('#formModuleSelect').val(data.parent_id);
								$("#formHrefInput").attr("disabled",false);
							    $("#formHrefInput").removeClass("layui-disabled");
								$('#formHrefInput').val(data.href);
							}else if(data.type == "2"){
								$("#formMenuSelect").attr("disabled",false);
								$('#formMenuSelect').val(data.parent_id);
								$("#formHrefInput").attr("disabled",false);
							    $("#formHrefInput").removeClass("layui-disabled");
								$('#formHrefInput').val(data.href);
							}else{
								
							}
							$('#formTitleInput').val(data.title);
							var btn = layero.find('.layui-layer-btn');
							btn.css('text-align', 'center');
							/* 渲染表单 */
							form.render();
						},
						yes: function(index, layero){
							var formTypeSelect =  $("#formTypeSelect").val();
							var formHrefInput =  $("#formHrefInput").val();
							var formMenuSelect =  $("#formMenuSelect").val();
							var formModuleSelect =  $("#formModuleSelect").val();
							var formTitleInput =  $("#formTitleInput").val();
							var object = {};
							object["id"] = data.id;
							if(formTypeSelect == "3"){
								if(formHrefInput == "" || formHrefInput == null){
									layer.msg("路径不能为空");
									return;
								}
								if(formModuleSelect == "" || formModuleSelect == null){
									layer.msg("父模块不能为空");
									return;
								}
								if(formTitleInput == "" || formTitleInput == null){
									layer.msg("名称不能为空");
									return;
								}
								object["title"] = formTitleInput;
								object["type"] = formTypeSelect;
								object["parent_id"] = formModuleSelect;
								object["href"] = formHrefInput;
							}else if (formTypeSelect == "2"){
								if(formMenuSelect == "" || formMenuSelect == null){
									layer.msg("父菜单不能为空");
									return;
								}
								if(formTitleInput == "" || formTitleInput == null){
									layer.msg("名称不能为空");
									return;
								}
								object["title"] = formTitleInput;
								object["type"] = formTypeSelect;
								object["parent_id"] = formMenuSelect;
								object["href"] = formHrefInput;
							}else if(formTypeSelect == "1"){
								if(formTitleInput == "" || formTitleInput == null){
									layer.msg("名称不能为空");
									return;
								}
								object["title"] = formTitleInput;
								object["type"] = formTypeSelect;
							}else{
								layer.msg("请选先择类型");
								return;
							}
							 $.ajax({ 
							       type: "post", 
							       contentType: "application/json;charset=utf-8",
							       url: "../../syspermission/updateSyspermission", 
							       data: JSON.stringify(object), 
							       success: function(data){
							    	  if(data == "0"){
							    		  layer.msg("更新权限失败");
							    		  layer.close(index);
							    	  }else if(data == "1"){
							    		  layer.msg("更新权限成功");
							    		  layer.close(index);
							    	  }else{
							    		  layer.msg("未知错误");
							    	  }
							       } 
							});
						}						
					});
				}
			});
			
			
			function userDelete(id){
				
			}
	
	 
});

